package com.fesine.produce;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2017/7/28 16:08
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/7/28 16:08
 */
public class ProduceTest {
    /* 定义简单队列，初始100个为0的数组*/
    private int[] quen = new int[100];
    private int count = 1;
    /* 生产者队列游标 */
    private int proIdx = 0;
    /* 生产者队列锁*/
    private Object proLock = new Object();

    /* 消费者队列游标 */
    private int conIdx = 0;
    /* 消费者队列锁*/
    private Object conLock = new Object();

    /**
     * 生产者工作
     */
    public void provider(){
        //使用同步代码块
        synchronized (proLock) {
            //当生产者队列游标和数组长度相同时，则游标归0
            if (proIdx == quen.length) {
                proIdx = 0;
            }
            //当数组对应下标值不为初始值0时，说明队列已满
            if (0 != quen[proIdx]) {
                System.out.println("队列已满。。。");
                return;
            }
            System.out.println("生产数据。。。"+count);
            quen[proIdx++] = count++;
        }
    }

    public int consumer(){
        //消费者同步代码块
        synchronized (conLock){
            //当消费者队列游标和数组长度相同时，则游标归0
            if (conIdx == quen.length) {
                conIdx = 0;
            }
            //当数组值为0时，说明已经消费完全
            if (0 == quen[conIdx]) {
                System.out.println("队列已空。。。");
            }
            return quen[conIdx++];
        }
    }

    public static void main(String[] args) {
        final ProduceTest test = new ProduceTest();
        //定义3个线程的线程池，提供者使用
        ExecutorService ptp = Executors.newFixedThreadPool(3);
        //定义2个线程的线程池，消费者使用
        ExecutorService ctp = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 30; i++) {
            ptp.execute(new Runnable() {
                @Override
                public void run() {
                    test.provider();
                }
            });
        }
        for (int i = 0; i < 31; i++) {
            ctp.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("消费。。。"+test.consumer());
                }
            });
        }

    }
}
